﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mortgage.UserControl;
using System.Web.Security;

namespace Mortgage.Account
{
    public partial class ManageUsers : System.Web.UI.Page
    {
        Mortgage.Srv.ICredentialsSrv srvCredential = Mortgage.Srv.SrvFactory.CreateCredentialsSrv();

        #region Event Handler

        protected void Page_Load(object sender, EventArgs e)
        {
            this.grdUsers.RowDataBound += new GridViewRowEventHandler(grdUsers_RowDataBound);
            if (!this.Page.IsPostBack)
            {
                grdUsers.PageIndex = 1;
                BindGridView();
                BindRole();
                FormMode = EnmFormMode.Blank;
                HandleFormState(FormMode);
            }

        }

        void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
                e.Row.Attributes["onmouseout"] = "this.style.cursor='default';";

                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grdUsers, "Select$" + e.Row.RowIndex);
            }
        }

        protected void custPager_PageChanged(object sender, CustomPageChangeArgs e)
        {
            grdUsers.PageSize = e.CurrentPageSize;
            grdUsers.PageIndex = e.CurrentPageNumber;


            BindGridView();
            HandleFormState(FormMode);
        }

        protected void grdUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            string userName = grdUsers.DataKeys[grdUsers.SelectedIndex].Value.ToString();
            MembershipUser usr = srvCredential.GetMemberShipById(userName);
            if (Entity == null)
                Entity = new BindMembershipUser();
            else
                Entity = new BindMembershipUser(usr);

            // Update mode
            FormMode = EnmFormMode.Edit;
            HandleFormState(FormMode);
            BindView();




        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            // Update mode
            Entity = new BindMembershipUser();
            FormMode = EnmFormMode.Insert;
            HandleFormState(FormMode);
            BindView();

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;
            BindEntity();
            // clear error Message
            DialogMess.Text = string.Empty;
            DialogMess.CssClass = "successBox";
            string userName;
            userName = Entity.UserName;
            if (FormMode == EnmFormMode.Insert) // Insert Mode
            {
                //MembershipCreateStatus crtStatus = new MembershipCreateStatus();
                try
                {
                    MembershipUser insObj = Membership.CreateUser(Entity.UserName, Entity.Password, Entity.Email);

                    insObj.Comment = Entity.Comment;
                    insObj.IsApproved = fldIsApproved.Checked;

                    Membership.UpdateUser(insObj);
                    UpdateRole(userName);
                    DialogMess.Text = "Cập nhật thành công!";
                    BindGridView();

                    // Translate to update mode
                    // Update mode
                    FormMode = EnmFormMode.Edit;
                    HandleFormState(FormMode);
                    BindView();
                }
                catch (Exception ex)
                {
                    DialogMess.Text = ex.Message;
                    DialogMess.CssClass = "failureBox";
                }


            }
            else
            {

                MembershipUserCollection updObjCollection = Membership.FindUsersByName(Entity.UserName);
                if (updObjCollection.Count <= 0)
                {
                    DialogMess.Text = "Tài khỏan không tồn tại! Thử refresh page!";
                    DialogMess.CssClass = "failureBox";
                }
                else
                {
                    MembershipUser usr = updObjCollection[Entity.UserName];
                    if (!string.IsNullOrEmpty(fldPassword.Text))
                    {
                        string resetPass = usr.ResetPassword();
                        usr.ChangePassword(resetPass, Entity.Password);
                    }

                    usr.Comment = Entity.Comment;
                    usr.Email = Entity.Email;
                    usr.IsApproved = Entity.IsApproved;

                    Membership.UpdateUser(usr);
                    UpdateRole(userName);
                    DialogMess.Text = "Cập nhật thành công!";
                    BindGridView();

                    // Translate to update mode
                    // Update mode
                    FormMode = EnmFormMode.Edit;
                    HandleFormState(FormMode);
                    BindView();
                }

            }
          
        }

        void UpdateRole(string userName)
        {
            // Update roles for user
            string r;
            foreach (ListItem i in lstRole.Items)
            {
                r = i.Value;
                try
                {
                    if (i.Selected)
                    {
                        Roles.AddUsersToRole(new string[] { userName }, r);
                    }
                    else
                    {
                        Roles.RemoveUserFromRole(userName, r);
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Membership.DeleteUser(Entity.UserName);
            BindGridView();
            FormMode = EnmFormMode.Blank;
            HandleFormState(FormMode);
        }


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            FormMode = EnmFormMode.Blank;
            HandleFormState(FormMode);
        }
        #endregion

        #region Function

        protected void BindRole()
        {
            string[] roles=  Roles.GetAllRoles();
            foreach (string r in roles)
            {
                lstRole.Items.Add( new ListItem(r,r));
            }

        }

        protected void BindGridView()
        {
            int totalUser = 0;
            grdUsers.DataSource = Membership.GetAllUsers(grdUsers.PageIndex - 1, grdUsers.PageSize, out totalUser);
            custPager.CurrentPageNumber = grdUsers.PageIndex;
            custPager.TotalPages = (totalUser / grdUsers.PageSize) + 1;
            grdUsers.DataBind();
            if (totalUser <= 0)
                custPager.Visible = false;

        }

        #endregion

        #region Property

        public BindMembershipUser Entity
        {
            get
            {
                return ViewState["_Entity"] as BindMembershipUser;
            }
            set
            {
                ViewState["_Entity"] = value;
            }
        }

        public EnmFormMode FormMode
        {
            get
            {
                if (ViewState["_ViewState"] == null)
                    return EnmFormMode.Blank;
                EnmFormMode result = (EnmFormMode)Enum.Parse(typeof(EnmFormMode), ViewState["_ViewState"].ToString());
                return result;

            }
            set
            {
                ViewState["_ViewState"] = value;
            }
        }

        #endregion

        #region Binding

        protected void HandleFormState(EnmFormMode state)
        {
            switch (state)
            {
                case EnmFormMode.Blank:
                    btnCancel.Enabled = false;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = true;
                    btnSave.Enabled = false;


                    BlankControl();
                    EnableControl(false);
                    Entity = new BindMembershipUser();

                    break;
                case EnmFormMode.Edit:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = !(Membership.GetAllUsers().Count <= 1);
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;
                    reqfldPassword.Enabled = false;
                    reqfldConfirmPassword.Enabled = false;
                    EnableControl(true);
                    fldUserName.Enabled = false;
                    break;
                case EnmFormMode.Insert:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = false;
                    btnSave.Enabled = true;
                    reqfldPassword.Enabled = true;
                    reqfldConfirmPassword.Enabled = true;
                    EnableControl(true);

                    break;
            }

            BindView();
        }

        protected void EnableControl(bool enable)
        {

            fldUserName.Enabled = enable;
            fldPassword.Enabled = enable;
            fldEmail.Enabled = enable;
            fldIsApproved.Enabled = enable;
            fldComment.Enabled = enable;
            fldConfirmPassword.Enabled = enable;
            lstRole.Enabled = enable;
        }

        protected void BindView()
        {

            fldUserName.Text = Entity.UserName;
            fldEmail.Text = Entity.Email;
            fldComment.Text = Entity.Comment;
            fldPassword.Text = Entity.Password;
            fldIsApproved.Checked = Entity.IsApproved;
            if (!string.IsNullOrEmpty(Entity.UserName))
            {
                string r;
                foreach (ListItem i in lstRole.Items)
                {
                    r = i.Value;
                    i.Selected = Roles.IsUserInRole(Entity.UserName, r);
                }
            }

        }

        protected void BindEntity()
        {
            BindMembershipUser usr = new BindMembershipUser();
            usr.Password = fldPassword.Text;
            usr.UserName = fldUserName.Text.Trim();
            usr.Comment = fldComment.Text.Trim();
            usr.Email = fldEmail.Text.Trim();
            usr.IsApproved = fldIsApproved.Checked;
            Entity = usr;
        }

        protected void BlankControl()
        {
            fldUserName.Text = string.Empty;
            fldComment.Text = string.Empty;
            fldConfirmPassword.Text = string.Empty;
            fldEmail.Text = string.Empty;
            fldIsApproved.Checked = false;
            fldPassword.Text = string.Empty;

            foreach (ListItem i in lstRole.Items)
            {

                i.Selected = false;
            }
            DialogMess.CssClass = string.Empty;
            DialogMess.Text = string.Empty;

        }

        #endregion




    }

    [Serializable]
    public class BindMembershipUser
    {
        public string UserName;
        public string Comment;
        public string Password;
        public string Email;
        public bool IsApproved;

        public BindMembershipUser()
        {
            IsApproved = true;
        }

        public BindMembershipUser(MembershipUser usr)
        {
            this.UserName = usr.UserName;
            this.Comment = usr.Comment;
            this.Email = usr.Email;
            this.IsApproved = usr.IsApproved;
            this.Password = "password";
        }

    }
}